//
// Created by xming-kaede on 2024/7/4.
//
#include <procedure.h>
#include <network.h>
#include <netdata.h>
#include <cstdio>
#include <cstring>
#include <UI.h>

//client
bool IsHost = false;
bool ClientPlayerList[4];
int myId = -1;
bool JoinRoom(char* serverAddrStr) {
    if(!ConnectServer(serverAddrStr)) {
        printf("连接服务器失败\n");
        return false;
    }
    printf("连接服务器成功\n");
    StopFindRoom();
    RegisterServerMessageHandler(ParseAndHandleRoomPackFromServer);
    SetClientDisconnectHandler(OnPlayerQuit);
    SetLostConnectionHandler(OnDisconnectServer);
    SendJoinRequest();
    return true;
}
void SetMyId(int id) {
    printf("我的id是%d\n",id);
    myId = id;
}
void UpdateClientPlayerList(const char *list) {
    memset(&ClientPlayerList, 0, 4);
    while(*list != ']') {
        ClientPlayerList[*list & 0x0f] = true;
        printf("玩家列表%d\n",*list & 0x0f);
        list++;
    }
}

//server
bool IsPlayerResponsedGameStart[4];
Room LocalRoom = {UNAVAILABLE,0,nullptr};
bool StartRoom(char* RoomInfo)
{
    LocalRoom.Status = AVAILABLE;
    LocalRoom.Info = RoomInfo;
    LocalRoom.PlayerIps = new char*[4];
    IsHost = true;
    if(!StartBroadcast()) {
        printf("创建房间失败,错误1\n");
        return false;
    }
    if(!StartServer()) {
        printf("创建房间失败，错误2\n");
        return false;
    }
    RegisterClientMessageHandler(ParseAndHandleRoomPackFromClient);
    return true;
}
void CloseRoom()
{
    LocalRoom.Status = UNAVAILABLE;
    LocalRoom.Info = nullptr;
    delete LocalRoom.PlayerIps;
    for (int i = 0; i < LocalRoom.OnlinePlayerCount; ++i) {
        delete LocalRoom.PlayerIps[i];
    }
    for (int i = 0; i < 4; ++i) {
        IsPlayerResponsedGameStart[i] = false;
    }
    SendRoomOverPack();
    StopBroadcast();
    CloseServer();
}
void GenerateLocalRoomInfo(char *buffer)
{
    sprintf(buffer,"<[%d%s]>",LocalRoom.OnlinePlayerCount,LocalRoom.Info);
}
bool IsAllPlayerReadyToStart()
{
    bool ready = true;
    for (int i = 0; i < 4; ++i) {
        if (IsClientOnline(i) && !IsPlayerResponsedGameStart[i])
            ready = false;
    }
    return ready;
}